package com.xianyun.book.gatewayimpl;

import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.Assert;
import com.xianyun.book.common.core.event.DomainEventPublisher;
import com.xianyun.book.convertor.OrderConvertor;
import com.xianyun.book.domain.book.Book;
import com.xianyun.book.domain.book.BookFineness;
import com.xianyun.book.domain.gateway.BookGateway;
import com.xianyun.book.domain.gateway.OrderGateway;
import com.xianyun.book.domain.order.Order;
import com.xianyun.book.domain.order.OrderStatus;
import com.xianyun.book.domain.order.OrderType;
import com.xianyun.book.domain.order.SalesOrder;
import com.xianyun.book.domain.pay.PayStatus;
import com.xianyun.book.dto.domainevent.OrderBuyCreateEvent;
import com.xianyun.book.gatewayimpl.database.OrderMapper;
import com.xianyun.book.gatewayimpl.database.dataobject.OrderDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author ytt
 */
@Slf4j
@Component
public class OrderGatewayImpl implements OrderGateway {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private BookGateway bookGateway;

    @Resource
    private DomainEventPublisher domainEventPublisher;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public String createBookOrder(SalesOrder salesOrder) {
        String orderId = UUID.randomUUID().toString();
        log.info("创建购买订单！user:{},订单编号:{}",salesOrder.getUserSecurity(),orderId);
        String relateId = getRelateOrderId(salesOrder.getIsbn(), salesOrder.getBuyNumber());
        Assert.notNull(relateId,"暂无匹配的交易订单!");
        OrderDO dateOrder = new OrderDO();
        BeanUtils.copyProperties(salesOrder,dateOrder);
        dateOrder.setOrderId(orderId);
        dateOrder.setIsbn(salesOrder.getIsbn());
        dateOrder.setPayStatus(PayStatus.WAIT_CONFIRM.getPayStatusId());
        dateOrder.setRelateOrderId(relateId);
        dateOrder.setOrderType(OrderType.BUYER.getOrderType());
        dateOrder.setOrderStatus(OrderStatus.WAIT_CONFIRM.getStatusId());
        dateOrder.setBookNumber(salesOrder.getBuyNumber());
        dateOrder.setTotalPrice(getTotalPrice(salesOrder));
        dateOrder.setUserId(salesOrder.getUserSecurity());
        orderMapper.createOrder(dateOrder);
        initOrderBuyCreateEventAndSend(dateOrder);
        return orderId;
    }

    @Override
    public String createBookSellOrder(SalesOrder salesOrder) {
        String orderId = UUID.randomUUID().toString();
        log.info("创建售出订单！user:{},订单编号:{}",salesOrder.getUserSecurity(),orderId);
        OrderDO dateOrder = new OrderDO();
        dateOrder.setOrderId(orderId);
        dateOrder.setIsbn(salesOrder.getIsbn());
        dateOrder.setBookNumber(salesOrder.getSellNumber());
        dateOrder.setOrderStatus(OrderStatus.WAIT_SOLD.getStatusId());
        dateOrder.setTotalPrice(getTotalPrice(salesOrder));
        dateOrder.setUserId(salesOrder.getUserSecurity());
        dateOrder.setOrderType(OrderType.SELLER.getOrderType());
        orderMapper.createOrder(dateOrder);
        return orderId;
    }

    @Override
    public void updateOrder(SalesOrder salesOrder) {
        orderMapper.updateOrder(new OrderDO());
    }

    @Override
    public void cancelOrder(String orderId) {
        orderMapper.updateOrder(new OrderDO());
    }

    @Override
    public Order getOrderInfoById(String orderId) {
        OrderDO result = orderMapper.getOrderInfoById(orderId);
        return new Order();
    }

    @Override
    public List<Order> listInSellOrdersByIsbn(String isbn) {
        List<OrderDO> resultData = orderMapper.selectInSellOrdersByIsbn(isbn);
        return OrderConvertor.toDataTranslateList(resultData);
    }

    private String getRelateOrderId(String isbn,Integer bookNumber) {
        List<Order> orderList = listInSellOrdersByIsbn(isbn);
        Assert.notEmpty(orderList,"暂时没有在售订单，请等待！");
        return orderList.stream().filter(order -> order.getBookNumber().equals(bookNumber)).collect(Collectors.toList()).get(0).getOrderId();
    }

    private BigDecimal getTotalPrice(SalesOrder salesOrder){
        Book resultBook = bookGateway.saveOrQueryBookByIsbn(salesOrder.getIsbn());
        resultBook.setFineness(BookFineness.getBookFinenessByStatus(salesOrder.getFinenessType()));
        if (salesOrder.isBuyer()){
            return resultBook.countBookRealPrice().multiply(new BigDecimal(salesOrder.getBuyNumber()));
        } else {
            return resultBook.countBookRealPrice().multiply(new BigDecimal(salesOrder.getSellNumber()));
        }
    }


    private void initOrderBuyCreateEventAndSend(OrderDO orderDO){
        OrderBuyCreateEvent createEvent = new OrderBuyCreateEvent();
        createEvent.setIsbn(orderDO.getIsbn());
        createEvent.setOrderId(orderDO.getOrderId());
        createEvent.setRelateOrderId(orderDO.getRelateOrderId());
        createEvent.setPayStatus(PayStatus.WAIT_CONFIRM.getPayStatusId());
        domainEventPublisher.publish(createEvent);
    }
}
